﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace AB.Common
{
    /// <summary>
    /// Http帮助类
    /// </summary>
    public class HttpHelper
    {
        /// <summary>
        /// POST
        /// </summary>
        /// <param name="postDataStr"></param>
        /// <param name="url"></param>
        /// <param name="ContentType"></param>
        /// <param name="Timeout"></param>
        /// <returns></returns>
        public static string Post(string postDataStr, string url,string ContentType= "application/json;charset=utf-8",int Timeout = 120000)
        {
            string content = string.Empty;
            if (!string.IsNullOrEmpty(url))
            {
                Encoding encoding = Encoding.UTF8;
                string strUrl = url;
                byte[] data = encoding.GetBytes(postDataStr);
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(strUrl);
                myRequest.Method = "POST";
                myRequest.KeepAlive = false;
                myRequest.ContentType = ContentType;
                myRequest.ContentLength = data.Length;
                myRequest.Timeout = Timeout;
                myRequest.ReadWriteTimeout = Timeout;
                Stream newStream = myRequest.GetRequestStream();// 发送数据 
                newStream.Write(data, 0, data.Length);
                newStream.Close();
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                content = reader.ReadToEnd();
                reader.Dispose();
                myResponse.Close();
                return content;
            }
            return null;
        }
        /// <summary>
        /// GET
        /// </summary>
        /// <param name="DataStr"></param>
        /// <param name="url"></param>
        /// <param name="Timeout"></param>
        /// <returns></returns>
        public static string Get(string DataStr, string url, int Timeout = 120000)
        {
            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url + "?" + DataStr);
            httpRequest.Timeout = Timeout;
            httpRequest.Method = "GET";
            HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            StreamReader sr = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8);
            string result = sr.ReadToEnd();
            result = result.Replace("\r", "").Replace("\n", "").Replace("\t", "");
            int status = (int)httpResponse.StatusCode;
            sr.Close();
            return result;
        }
    }
}
